//
//  ViewController.m
//  ZLSwipeableViewDemo
//
//  Created by Zhixuan Lai on 11/1/14.
//  Copyright (c) 2014 Zhixuan Lai. All rights reserved.
//

#import "ZLSwipeableViewController.h"
#import "UIColor+FlatColors.h"  
#import "CardView.h"
#import "TextViewController.h"
@interface ZLSwipeableViewController ()

@property (nonatomic, strong) NSArray *colors;
@property (nonatomic) NSUInteger colorIndex;

@property (nonatomic) BOOL loadCardFromXib;

@property (nonatomic, strong) UIBarButtonItem *leftBarButtonItem;
@property (nonatomic, strong) UIBarButtonItem *rightBarButtonItem;
@property (nonatomic, strong) UIButton  * supportButtonItem;
@property (nonatomic, strong) UIButton  * notSupportButtonItem;
@end

@implementation ZLSwipeableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"消息";
    self.navigationController.toolbarHidden = NO;
    self.view.clipsToBounds = YES;
    self.view.backgroundColor = [UIColor whiteColor];

    // Do any additional setup after loading the view, typically from a nib.
    self.colorIndex = 0;
    self.colors = @[
        @"Turquoise",
        @"Green Sea",
        @"Emerald",
        @"Nephritis",
        @"Peter River",
        @"Belize Hole",
        @"Amethyst",
        @"Wisteria",
        @"Wet Asphalt",
        @"Midnight Blue",
        @"Sun Flower",
        @"Orange",
        @"Carrot",
        @"Pumpkin",
        @"Alizarin",
        @"Pomegranate",
        @"Clouds",
        @"Silver",
        @"Concrete",
        @"Asbestos"
    ];

    

    ZLSwipeableView *swipeableView = [[ZLSwipeableView alloc] initWithFrame:CGRectZero];
    self.swipeableView = swipeableView;
    
    [self.view addSubview:self.swipeableView];
    [self addButton];
    // Required Data Source
    self.swipeableView.dataSource = self;

    // Optional Delegate
    self.swipeableView.delegate = self;

    self.swipeableView.translatesAutoresizingMaskIntoConstraints = NO;
    
    NSDictionary *metrics = @{};

    [self.view addConstraints:[NSLayoutConstraint
                                  constraintsWithVisualFormat:@"|-50-[swipeableView]-50-|"
                                                      options:0
                                                      metrics:metrics
                                                        views:NSDictionaryOfVariableBindings(
                                                                  swipeableView)]];

    [self.view addConstraints:[NSLayoutConstraint
                                  constraintsWithVisualFormat:@"V:|-30-[swipeableView]-190-|"
                                                      options:0
                                                      metrics:metrics
                                                        views:NSDictionaryOfVariableBindings(
                                                                  swipeableView)]];
    
}


-(void)addButton{

#define btnwidth  [[UIScreen mainScreen] bounds].size.width/6
#define btnHeight  [[UIScreen mainScreen] bounds].size.width/8
#define space     [[UIScreen mainScreen] bounds].size.width/5
#define upSpace     [[UIScreen mainScreen] bounds].size.width/4
    self.supportButtonItem = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.supportButtonItem.frame = CGRectMake(space, Screen_Height - upSpace - 49 - 64, btnwidth, btnwidth);
    [self.supportButtonItem setBackgroundImage:[UIImage imageNamed:@"喜欢"] forState:UIControlStateNormal];
    [self.supportButtonItem addTarget:self action:@selector(handleLeft:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.supportButtonItem];

    self.notSupportButtonItem = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.notSupportButtonItem.frame = CGRectMake(Screen_Width/2 + space - 15, Screen_Height - upSpace - 49 - 64, btnwidth, btnwidth);
    [self.notSupportButtonItem setBackgroundImage:[UIImage imageNamed:@"不喜欢"] forState:UIControlStateNormal];
    [self.notSupportButtonItem addTarget:self action:@selector(handleRight:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.notSupportButtonItem];



}


- (void)viewDidLayoutSubviews {
    [self.swipeableView loadViewsIfNeeded];
}
#pragma mark - Action

- (void)handleLeft:(UIBarButtonItem *)sender {
    [self.swipeableView swipeTopViewToLeft];
}

- (void)handleRight:(UIBarButtonItem *)sender {
    [self.swipeableView swipeTopViewToRight];
}


#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    self.loadCardFromXib = buttonIndex == 1;
    self.colorIndex = 0;
    [self.swipeableView discardAllViews];
    [self.swipeableView loadViewsIfNeeded];
}

#pragma mark - ZLSwipeableViewDelegatedirection


- (void)swipeableView:(ZLSwipeableView *)swipeableView
         didSwipeView:(UIView *)view
          inDirection:(ZLSwipeableViewDirection)direction {
    NSLog(@"did swipe in direction: %zd", direction);
    if (direction == 1) {
        //if (![[NSUserDefaults standardUserDefaults]  boolForKey:@"right"]) {
            
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"left"];
        //[[NSNotificationCenter defaultCenter]postNotificationName:NOTIFICATION_UPDATE_MUSCI_CURRENT_INDEX object:[NSNumber numberWithLong:indexPath.item]];
        //}
    }else {
        
           [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"right"];
    
    }
    
}

- (void)swipeableView:(ZLSwipeableView *)swipeableView didCancelSwipe:(UIView *)view {
    NSLog(@"did cancel swipe");
}


//开始拖动
- (void)swipeableView:(ZLSwipeableView *)swipeableView
  didStartSwipingView:(UIView *)view
           atLocation:(CGPoint)location {
    NSLog(@"did start swiping at location: x %f, y %f", location.x, location.y);
    
        self.supportButtonItem.alpha = 1.0;

        self.notSupportButtonItem.alpha  = 1.0;

}

- (void)swipeableView:(ZLSwipeableView *)swipeableView
          swipingView:(UIView *)view
           atLocation:(CGPoint)location
          translation:(CGPoint)translation {
    NSLog(@"swiping at location: x %f, y %f, translation: x %f, y %f", location.x, location.y,
          translation.x, translation.y);
    float newAlpha = translation.x / swipeableView.frame.size.width;
    if ([[NSUserDefaults standardUserDefaults]  boolForKey:@"left"]){
        
        self.notSupportButtonItem.alpha =  -newAlpha;
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"left"];
    }else if ([[NSUserDefaults standardUserDefaults]  boolForKey:@"right"]){
        
        self.supportButtonItem.alpha  = newAlpha;
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"right"];

    }
}


//结束拖动
- (void)swipeableView:(ZLSwipeableView *)swipeableView
    didEndSwipingView:(UIView *)view
           atLocation:(CGPoint)location {
    NSLog(@"did end swiping at location: x %f, y %f", location.x, location.y);
    self.supportButtonItem.alpha = 1.0;
    self.notSupportButtonItem.alpha  = 1.0;
//    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"left"];
//    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"right"];

}

#pragma mark - ZLSwipeableViewDataSource

- (UIView *)nextViewForSwipeableView:(ZLSwipeableView *)swipeableView {
    if (self.colorIndex >= self.colors.count) {
        self.colorIndex = 0;
    }

    CardView *view = [[CardView alloc] initWithFrame:swipeableView.bounds];
    // 单击的 Recognizer
    UITapGestureRecognizer* singleRecognizer;
    singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(SingleTap:)];
    //点击的次数
    singleRecognizer.numberOfTapsRequired = 1; // 单击
    
    //给self.view添加一个手势监测；
    
    [view addGestureRecognizer:singleRecognizer];
    
    
    // 双击的 Recognizer
    UITapGestureRecognizer* doubleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(DoubleTap:)];
    doubleRecognizer.numberOfTapsRequired = 2; // 双击
    //关键语句，给self.view添加一个手势监测；
    [view addGestureRecognizer:doubleRecognizer];
    
    // 关键在这一行，双击手势确定监测失败才会触发单击手势的相应操作
    [singleRecognizer requireGestureRecognizerToFail:doubleRecognizer];
    UIImageView * textView = [[UIImageView alloc]initWithFrame:swipeableView.bounds];
    textView.backgroundColor = [UIColor clearColor];
    textView.image = [UIImage imageNamed:@"文章消息"];
    [view addSubview:textView];
//    view.backgroundColor = [self colorForName:self.colors[self.colorIndex]];
    view.backgroundColor = [UIColor whiteColor];
    self.colorIndex++;

    if (self.loadCardFromXib) {
        UIView *contentView =
            [[NSBundle mainBundle] loadNibNamed:@"CardContentView" owner:self options:nil][0];
        contentView.translatesAutoresizingMaskIntoConstraints = NO;
        [view addSubview:contentView];

        // This is important:
        // https://github.com/zhxnlai/ZLSwipeableView/issues/9
        NSDictionary *metrics =
            @{ @"height" : @(view.bounds.size.height),
               @"width" : @(view.bounds.size.width) };
        NSDictionary *views = NSDictionaryOfVariableBindings(contentView);
        [view addConstraints:[NSLayoutConstraint
                                 constraintsWithVisualFormat:@"H:|[contentView(width)]"
                                                     options:0
                                                     metrics:metrics
                                                       views:views]];
        [view addConstraints:[NSLayoutConstraint
                                 constraintsWithVisualFormat:@"V:|[contentView(height)]"
                                                     options:0
                                                     metrics:metrics
                                                       views:views]];
    }
    return view;
}


-(void)SingleTap:(UITapGestureRecognizer*)recognizer
{
    //处理单击操作
    TextViewController * textVC = [[TextViewController alloc]init];
    textVC.index = self.colorIndex;
    [self.navigationController pushViewController:textVC animated:YES];
}

-(void)DoubleTap:(UITapGestureRecognizer*)recognizer
{
//    //处理双击操作
//    TextViewController * textVC = [[TextViewController alloc]init];
//    textVC.index = self.colorIndex;
//    [self.navigationController pushViewController:textVC animated:YES];
}


#pragma mark - ()

//- (UIColor *)colorForName:(NSString *)name {
//    NSString *sanitizedName = [name stringByReplacingOccurrencesOfString:@" " withString:@""];
//    NSString *selectorString = [NSString stringWithFormat:@"flat%@Color", sanitizedName];
//    Class colorClass = [UIColor class];
//    return [colorClass performSelector:NSSelectorFromString(selectorString)];
//}

@end
